/**
 * 特殊时段通联分析器 - 对象中心化版本
 * 检测深夜等特殊时段的高频通话
 */

class IntimacyAnalyzer extends BaseAnalyzer {
  constructor(caseId, targetSubject = null) {
    super(caseId, targetSubject);
    this.name = '特殊时段通联';
    this.description = '检测深夜等特殊时段的高频通话，识别亲密关系';
  }

  async analyze(params = {}) {
    const nightStart = params.nightStart || 22;
    const nightEnd = params.nightEnd || 6;
    const minCalls = params.minCalls || 3;

    const phoneFilter = this.getPhoneFilter();

    const sql = `
            SELECT 
                user_number,
                user_name,
                opp_user_number,
                COUNT(*) as total_calls,
                SUM(duration) as total_duration,
                SUM(CASE WHEN CAST(strftime('%H', start_time) AS INTEGER) >= ? 
                         OR CAST(strftime('%H', start_time) AS INTEGER) < ? 
                    THEN 1 ELSE 0 END) as night_calls,
                MIN(start_time) as first_call,
                MAX(start_time) as last_call
            FROM call_records
            WHERE case_id = ?
                ${phoneFilter}
            GROUP BY user_number, opp_user_number
            HAVING night_calls >= ?
            ORDER BY night_calls DESC, total_calls DESC
            LIMIT 100
        `;

    const result = await this.runQuery(sql, [
      nightStart,
      nightEnd,
      this.caseId,
      minCalls
    ]);

    if (!result.success) {
      return this.createResult('intimacy', this.name, [], '查询失败: ' + result.message, 'danger');
    }

    const data = result.data;
    const summary = data.length > 0
      ? `检测到 ${data.length} 个特殊时段高频通联关系，深夜通话共 ${data.reduce((sum, r) => sum + r.night_calls, 0)} 次`
      : '未检测到特殊时段高频通联';

    const level = data.length > 10 ? 'warning' : (data.length > 0 ? 'info' : 'info');

    return this.createResult('intimacy', this.name, data, summary, level);
  }

  renderResult(data) {
    if (!data || data.length === 0) {
      return '<div class="empty-result" style="padding:40px; text-align:center; color:#999;">✓ 未发现特殊时段通联异常</div>';
    }

    let html = `
      <div class="result-summary" style="padding:15px; background:#fff3cd; border-left:4px solid #ffc107; margin-bottom:15px;">
        <strong>💕 发现 ${data.length} 个特殊时段高频通联</strong>
        <p style="margin:5px 0 0; font-size:0.9rem;">深夜频繁通话，可能存在亲密关系或共谋行为</p>
      </div>
      
      <table class="analysis-result-table" style="width:100%; border-collapse:collapse; font-size:0.9rem;">
        <thead style="background:#f5f7fa;">
          <tr>
            <th style="padding:10px; border:1px solid #e0e0e0;">本机号码</th>
            <th style="padding:10px; border:1px solid #e0e0e0;">对方号码</th>
            <th style="padding:10px; border:1px solid #e0e0e0; text-align:center;">总通话次数</th>
            <th style="padding:10px; border:1px solid #e0e0e0; text-align:center; background:#fff3cd;">深夜通话</th>
            <th style="padding:10px; border:1px solid #e0e0e0;">通话时长(秒)</th>
          </tr>
        </thead>
        <tbody>
    `;

    data.forEach((row, index) => {
      const rowStyle = index % 2 === 0 ? 'background:#fafafa;' : '';
      const nightRatio = ((row.night_calls / row.total_calls) * 100).toFixed(0);
      html += `<tr style="${rowStyle}">`;
      html += `<td style="padding:8px; border:1px solid #e0e0e0;">${row.user_name || '-'}<br><small style="color:#909399; font-family:monospace;">${row.user_number}</small></td>`;
      html += `<td style="padding:8px; border:1px solid #e0e0e0; font-family:monospace; color:#409eff;">${row.opp_user_number}</td>`;
      html += `<td style="padding:8px; border:1px solid #e0e0e0; text-align:center;">${row.total_calls}</td>`;
      html += `<td style="padding:8px; border:1px solid #e0e0e0; text-align:center; font-weight:bold; color:#e6a23c;">${row.night_calls} (${nightRatio}%)</td>`;
      html += `<td style="padding:8px; border:1px solid #e0e0e0;">${row.total_duration || 0}</td>`;
      html += '</tr>';
    });

    html += '</tbody></table>';
    return html;
  }
}

window.IntimacyAnalyzer = IntimacyAnalyzer;
